package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface AddressRepository extends JpaRepository<DeliveryAddress, Long> {
    
    // 查询用户的所有地址
    List<DeliveryAddress> findByCustomer(User customer);
    
    // 查询用户的默认地址或非默认地址
    List<DeliveryAddress> findByCustomerAndIsDefault(User customer, Boolean isDefault);
    
    // 根据ID和用户查询地址
    Optional<DeliveryAddress> findByIdAndCustomer(Long id, User customer);
    
    // 查询用户的默认地址（返回单个结果）
    @Query("SELECT a FROM DeliveryAddress a WHERE a.customer = :customer AND a.isDefault = true") // 修改：Address → DeliveryAddress
    Optional<DeliveryAddress> findDefaultAddressByCustomer(@Param("customer") User customer);
    
    // 批量更新用户所有地址的默认状态（高性能）
    @Modifying
    @Query("UPDATE DeliveryAddress a SET a.isDefault = :isDefault WHERE a.customer = :customer") // 修改：Address → DeliveryAddress
    void updateDefaultStatusByCustomer(@Param("customer") User customer, @Param("isDefault") Boolean isDefault);
    
    // 统计用户地址数量
    long countByCustomer(User customer);
    
    // 检查地址是否属于用户
    boolean existsByIdAndCustomer(Long id, User customer);
    
    // 按创建时间降序获取用户地址
    List<DeliveryAddress> findByCustomerOrderByCreateTimeDesc(User customer);
    
    // 按联系人姓名模糊查询
    List<DeliveryAddress> findByCustomerAndContactNameContainingIgnoreCase(User customer, String contactName);
}
